<template>
    <dzs-dialog :title="title" :isShow="isShow" @close="onCancel" @open="onOpen">
        <dzs-form height="500px" :loadingOption="formInfo" :status="status" ref="myForm" v-model:value="formData"
            :options="formOptions" @onCancel="onCancel" @onSubmit="onSubmit">
        </dzs-form>
    </dzs-dialog>
</template>
<script setup lang="ts">
import { ref, computed , onMounted} from "vue";
import type { dzsFormProps } from "@/components/dzs-form/@types";
import type { dzsFormInstance } from "@/components/dzs-form";
import type { editFormData, addFormData } from "../@types";
import { ElNotification } from 'element-plus';
import { addArticle, updataArticle, getArticleById } from "../api/api";
import { uploadImg } from "@/api/api";
import { getNav } from "../../web-nav-manage/api/api"
import type { tableItem } from "../@types";
import type { CommonResponse } from "@/@types";
const emit = defineEmits(['cancel', 'update:isShow', 'onHoldSearch'])
const props = defineProps<{
    dialogData?: tableItem,
    status: string,
    isShow: boolean
}>()

const myForm = ref<dzsFormInstance>();
const typeList = ref<Array<{label : string, value : any}>>([])
const formData = ref<editFormData>({
    ID: "",
    title: "",
    brfie: "",
    imgUrl: "",
    reading: 10,
    typeID: "",
    content: "",
    keywords: "",
    more_meta: "",
    is_show: 1
})

const formInfo = ref({
    loading: false,
})

const title = computed(() => {
    return props.status === "add" ? "添加文章" : props.status === "edit" ? "编辑文章" : "查看文章详情"
})
const formOptions = computed<dzsFormProps['formOptions']>(() => {
    return {
        formProps: {
            "labelWidth": "100px"
        },
        formItem: [
            {
                label: "ID",
                type: "input",
                key: "ID",
                isHidden: true,
            },
            {
                label: "封面",
                type: "uploadImg",
                key: "imgUrl",
                props: {
                    openUploadFun: true,
                    uploadFun: (file: any, success: Function) => {
                        let formData = new FormData();
                        formData.append('file', file.raw);
                        uploadImg(formData).then((res: any) => {
                            success({ path: res.data.url }, {
                                ...file,
                                url: res.data.path +  res.data.url
                            })
                        })
                    }
                }
            },
            {
                label: "标题",
                type: "input",
                key: "title",
                rules: [
                    {
                        required: true,
                        message: "标题不能为空",
                        trigger: "blur"
                    }
                ]
            },
            {
                label: "简介",
                type: "input",
                key: "brfie",
                rules: [
                    {
                        required: true,
                        message: "简介不能为空",
                        trigger: "blur"
                    }
                ],
                props: {
                    type: "textarea",
                    rows: 4
                }
            },
            {
                label: "分类",
                type: "select",
                key: "typeID",
                children : typeList.value,
                rules: [
                    {
                        required: true,
                        message: "分类不能为空",
                        trigger: "change"
                    }
                ],
                span: 12
            },
            {
                label: "阅读量",
                type: "number",
                key: "reading",
                props: {
                    min: 0,
                    max: 10000000
                },
                span: 12
            },
            {
                label: "关键词",
                type: "input",
                key: "keywords",
                props : {
                    type: "textarea",
                    autosize: { minRows: 4, maxRows: 6 }
                }
            },
            {
                label: "更多元数据",
                type: "input",
                key: "more_meta",
                props : {
                    type: "textarea",
                    autosize: { minRows: 4, maxRows: 6 }
                },
                rules : [
                    // 校验是不是 JSONString
                    {
                        validator: (rule : any, value : any, callback : any) => {
                            if(!value){
                                callback();
                                return;
                            }
                            try {
                                JSON.parse(value);
                                callback();
                            } catch (error) {
                                callback(new Error("请输入正确的JSON字符串"));
                            }
                        },
                        trigger: "blur"
                    }
                ]
            },
            {
                label: "是否展示",
                type: "switch",
                key: "is_show",
                props: {
                    "active-value": 1,
                    "inactive-value": 0
                }
            },
            {
                label: "内容",
                type: "editor",
                key: "content",
                props: {
                    height: "500px"
                },
                rules: [
                    {
                        required: true,
                        message: "内容不能为空",
                        trigger: "blur"
                    }
                ]
            }
        ]
    }
})

onMounted(() => {
    onGetNav()
})

const onCancel = () => {
    myForm.value?.onCancel<editFormData>(false, {
        success: (res) => {
            formData.value = res
        }
    })
    emit('cancel');
    emit('update:isShow', false);
}


const onOpen = () => {
    if (props.dialogData?.ID) {
        // formData.value = props.dialogData
        getArticleById({
            ID: props.dialogData.ID
        }).then(res => {
            formData.value = res.data.data
        })
    }
}

const onSubmit = () => {
    formInfo.value.loading = true;
    if(Array.isArray(formData.value.imgUrl) && formData.value.imgUrl.length > 0){
        formData.value.imgUrl = formData.value.imgUrl[0].path;
    }
    if(typeof formData.value.imgUrl != 'string'){
        formData.value.imgUrl = '';
    }
    if (props.status === "edit") {
        updataArticle({
            ...formData.value
        }).then(res => {
            formInfo.value.loading = false;
            ElNotification({
                title: '成功',
                message: "提交成功",
                type: 'success'
            })
            emit("onHoldSearch");
            onCancel();
        }).catch(() => {
            formInfo.value.loading = false;
        })
        return;
    }
    addArticle({
        ...formData.value
    } as addFormData).then(res => {
        formInfo.value.loading = false;
        ElNotification({
            title: '成功',
            message: "提交成功",
            type: 'success'
        })
        emit("onHoldSearch");
        onCancel();
    }).catch(() => {
        formInfo.value.loading = false;
    })
}


const onGetNav = () => {
    getNav({
        isAdd: true
    }).then(res => {
        const result: CommonResponse<tableItem[]> = res;
        typeList.value = result.data.data.map((item: tableItem) => {
            return {
                label: item.title,
                value: item.ID
            }
        })
    })
}
</script>
<style scoped></style>